<template>
  <div class="approve-two-style">
    <zm-form size="small" :model="form" :rules="formRule" ref="zmForm">
      <div class="ma tc">
        <zm-button type="primary" size="normal" class="mb20" @click="addBranch">
          新增审批分支
        </zm-button>
      </div>
      <div class="tc mt30" v-if="!form.branchArr || form.branchArr.length <= 0">
        <div><i class="el-icon-box fs30"></i></div>
        <div class="mt20">暂无审批流设置,请先点击新增</div>
      </div>
      <div
        class="df-wrap df tc"
        style="justify-content: center;"
        v-if="form.branchArr && form.branchArr.length > 0"
      >
        <div
          class="w220 dib mr20 mb20"
          v-for="(item, index) in form.branchArr"
          :key="index"
        >
          <div class="tc mb10" v-if="!isAllDelete(item)">
            <span v-if="!item.isEditName">{{ item.flowName }}</span>
            <i
              v-if="!item.isEditName"
              class="el-icon-edit text-primary fs20 pointer"
              @click="editName(item, index)"
            ></i>
            <el-dropdown
              size="small"
              class="fr mr5"
              @command="handCommand(item, index)"
            >
              <span class="el-dropdown-link text-primary">...</span>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item command="delete">删除分支</el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
            <zm-form-item v-if="item.isEditName">
              <zm-input v-model="item.flowNameNew" class="w100"></zm-input>
              <i
                class="el-icon-circle-close fs20 text-error pointer"
                @click="cancelEdit(item, index)"
              ></i>
              <i
                class="el-icon-circle-check fs20 text-success pointer"
                @click="submitEdit(item, index)"
              ></i>
            </zm-form-item>
          </div>
          <div
            v-for="(objSpon, idxSpon) in item.nodeData.sponsorNode"
            :key="idxSpon + Math.random()"
          >
            <el-card class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>发起人</span>
              </div>
              <zm-form-item
                :prop="getProp(index, idxSpon, 'accountId', 'sponsorNode')"
                :rules="getRules('发起人')"
              >
                <select-people
                  :dis-account-id="disAccountId(objSpon.accountId)"
                  :row-info="objSpon"
                  :ini-label="getLabel(objSpon, departmentList)"
                  :department-list="departmentList"
                  @after-choose="
                    obj => {
                      afterChoose(
                        obj,
                        objSpon,
                        item,
                        item.nodeData.sponsorNode,
                        idxSpon
                      );
                    }
                  "
                >
                </select-people>
              </zm-form-item>
            </el-card>
          </div>
          <div
            v-for="(objAppro, idxAppro) in item.nodeData.approveNode"
            :key="idxAppro + Math.random()"
          >
            <div v-if="objAppro">
              <div class="vertical-line"></div>
              <div
                class="ma tc"
                @click="addCard(item.nodeData.approveNode, idxAppro, '2')"
              >
                <i class="el-icon-circle-plus fs20 text-primary"></i>
              </div>
              <div class="vertical-line"></div>
            </div>
            <el-card class="box-card bgcPurple" shadow="never">
              <div slot="header" class="clearfix">
                <span>审批人</span>
                <el-button
                  class="delete-button"
                  type="text"
                  @click="deleteCard(item.nodeData.approveNode, idxAppro)"
                >
                  <i class="el-icon-close fc-f"></i>
                </el-button>
              </div>
              <zm-form-item
                :prop="getProp(index, idxAppro, 'accountId', 'approveNode')"
                :rules="getRules('审批人')"
              >
                <select-people
                  :row-info="objAppro"
                  :ini-label="
                    getLabel(
                      objAppro,
                      objAppro.accountType === '1' ? departmentList : staffList
                    )
                  "
                  :department-list="departmentList"
                  :staff-list="staffList"
                  @after-choose="
                    obj => {
                      afterChoose(
                        obj,
                        objAppro,
                        item,
                        item.nodeData.approveNode,
                        idxAppro
                      );
                    }
                  "
                ></select-people>
              </zm-form-item>
            </el-card>
          </div>
          <div
            v-for="(objCopy, idxCopy) in item.nodeData.copyNode"
            :key="idxCopy + Math.random()"
          >
            <div v-if="objCopy">
              <div class="vertical-line"></div>
              <div
                class="ma tc"
                @click="addCard(item.nodeData.copyNode, idxCopy, '3')"
              >
                <i class="el-icon-circle-plus fs20 text-primary"></i>
              </div>
              <div class="vertical-line"></div>
            </div>
            <el-card class="box-card" shadow="never">
              <div slot="header" class="clearfix">
                <span>抄送人</span>
                <el-button
                  class="delete-button"
                  type="text"
                  @click="deleteCard(item.nodeData.copyNode, idxCopy)"
                >
                  <i class="el-icon-close fc-f"></i>
                </el-button>
              </div>
              <zm-form-item
                :prop="getProp(index, idxCopy, 'accountId', 'copyNode')"
                :rules="getRules('抄送人')"
              >
                <select-people
                  :row-info="objCopy"
                  :ini-label="
                    getLabel(
                      objCopy,
                      objCopy.accountType === '1' ? departmentList : staffList
                    )
                  "
                  :department-list="departmentList"
                  :staff-list="staffList"
                  @after-choose="
                    obj => {
                      afterChoose(
                        obj,
                        objCopy,
                        item,
                        item.nodeData.copyNode,
                        idxCopy
                      );
                    }
                  "
                ></select-people>
              </zm-form-item>
            </el-card>
          </div>
        </div>
      </div>
    </zm-form>
  </div>
</template>

<script>
import approveProcessApis from '@/api/src/approveProcess'
import publicApis from '@/api/src/public'
import SelectPeople from './SelectPeople'
import { defaultItem } from '../const'
export default {
  components: { SelectPeople },
  props: {
    value: {
      type: Object,
      default () {
        return {}
      }
    },
    processId: {
      type: String,
      default: ''
    }
  },
  data () {
    return {
      formRule: {},
      defaultItem,
      departmentList: [],
      staffList: [],
      deleteArr: []
    }
  },
  computed: {
    form: {
      get () {
        return this.value
      },
      set (val) {
        this.$emit('input', val)
      }
    }
  },

  created () {
    this.getTree()
    this.getStaff()
  },
  methods: {
    disAccountId (accountId) {
      let allAccountIds = []
      this.form.branchArr.forEach(i => {
        allAccountIds.push(i.nodeData.sponsorNode[0].accountId)
      })
      let nowAccountId = accountId.split(',')
      let ids = allAccountIds
        .join(',')
        .split(',')
        .filter(i => !nowAccountId.includes(i))
      return ids
    },
    isAllDelete (item) {
      // 所有卡片删光了
      if (
        item.nodeData.sponsorNode.length <= 0 &&
        item.nodeData.approveNode.length <= 0 &&
        item.nodeData.copyNode.length <= 0
      ) {
        return true
      } else {
        return false
      }
    },
    getProp (outIdx, index, label, nodeName) {
      return `branchArr[${outIdx}].nodeData.${nodeName}[${index}].${label}`
    },
    getRules (name) {
      let rule = [
        {
          required: true,
          message: `请选择${name}`
        }
      ]
      return rule
    },
    async getTree () {
      const _res = await publicApis.approveApartmentList()
      this.departmentList = _res
    },
    async getStaff () {
      const _res = await publicApis.getApproveAccountList()
      this.staffList = _res
    },
    getLabel (obj, array) {
      if (obj.accountId === '-1') {
        return '全部部门'
      } else {
        let labels = []
        let ids = obj.accountId ? obj.accountId.split(',') : []
        ids.forEach(x => {
          array.forEach(k => {
            if (obj.accountType === '1' && x === k.value) {
              labels.push(k.name)
            } else if (obj.accountType === '1' && k.children) {
              k.children.forEach(c => {
                if (x === c.value) {
                  labels.push(c.name)
                }
              })
            } else if (obj.accountType === '3' && k.accountData) {
              k.accountData.forEach(c => {
                if (x === c.id) {
                  labels.push(c.name)
                }
              })
            }
          })
        })
        return labels.join(',')
      }
    },
    async addBranch () {
      if (this.form.branchArr.length === 5) {
        this.$message.info('最多设置5个审批分支')
      } else {
        let flowName = `审批流分支${this.form.branchArr.length + 1}`
        const _res = await approveProcessApis.createFlow({
          processId: this.processId,
          flowName: flowName
        })
        const item = JSON.parse(JSON.stringify(this.defaultItem))
        this.form.branchArr.push({ ...item, flowName: flowName, flowId: _res })
      }
    },
    handCommand (item, index) {
      // 保存删除的id
      this.$confirm('确定删除该分支，将不可用', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      })
        .then(async () => {
          // await approveProcessApis.deleteFlow({ flowId: item.flowId })
          this.form.branchArr.splice(index, 1)
          this.deleteArr.push(item.flowId)
          this.form.cancelIds = this.deleteArr.join(',')
          this.$message({
            message: '操作成功',
            type: 'success'
          })
        })
        .catch(() => {})
    },
    editName (item) {
      this.$set(item, 'isEditName', true)
      this.$set(item, 'flowNameNew', item.flowName)
    },
    cancelEdit (item, index) {
      this.$set(item, 'isEditName', false)
    },
    async submitEdit (item, index) {
      await approveProcessApis.updateFlowName({
        id: item.flowId,
        flowName: item.flowNameNew
      })
      this.$set(item, 'isEditName', false)
      this.$set(item, 'flowName', item.flowNameNew)
    },
    async afterChoose (obj, objSpon, objOut, nodeItem, index) {
      let pId
      if (obj.nodeType !== '1') {
        pId = index > 0 ? nodeItem[index - 1].nodeId : '0'
      }
      if (objSpon.nodeId) {
        await approveProcessApis.updateFlowNode({
          id: objSpon.nodeId,
          accountType: obj.accountType,
          accountId: obj.accountId,
          pId: pId
        })
      } else {
        let createParams = {
          flowId: objOut.flowId,
          nodeType: objSpon.nodeType,
          accountType: obj.accountType,
          accountId: obj.accountId,
          pId: pId
        }
        let _res = await approveProcessApis.createFlowNode(createParams)
        this.$set(objSpon, 'nodeId', _res.nodeId)
      }
      this.$set(objSpon, 'accountId', obj.accountId)
      this.$set(objSpon, 'accountType', obj.accountType)
    },
    async deleteCard (item, index) {
      if (item[index].nodeId) {
        await approveProcessApis.deleteFlowNode({ id: item[index].nodeId })
        item.splice(index, 1)
      } else {
        item.splice(index, 1)
      }
    },
    addCard (item, index, nodeType) {
      let length = nodeType === '2' ? 10 : 5
      if (item.length >= length) {
        this.$message.info(`最多设置${length}个级别`)
      } else {
        let itemChild = {
          nodeId: '',
          nodeType: '',
          pId: '',
          accountType: '1',
          accountId: '',
          accountLabel: ''
        }
        // item.splice(index, 0, { ...itemChild, nodeType: nodeType })
        item.push({ ...itemChild, nodeType: nodeType })
      }
    },
    validate () {
      return this.$refs.zmForm
        ? this.$refs.zmForm.validate()
        : Promise.resolve()
    }
  }
}
</script>

<style lang="scss">
@import "~@/styles/variables.scss";
.approve-two-style {
  .box-card {
    position: relative;
    width: 100%;
    height: 100px;
    .el-card__body {
      padding: 15px 20px;
    }
    .delete-button {
      display: none;
      position: absolute;
      right: 5px;
      top: 12px;
    }
    .el-card__header {
      text-align: center;
      padding: 10px;
      background: $theme-primary;
      color: #fff;
    }
    .people-content {
      width: 100%;
      overflow: hidden;
      white-space: nowrap;
      text-overflow: ellipsis;
      -o-text-overflow: ellipsis;
    }
    .el-form-item__error {
      top: -12px;
      left: 48%;
      transform: translate(-50%, 0);
      font-size: 12px;
    }
  }
  .box-card:hover {
    .delete-button {
      display: block;
      padding: 0px;
    }
  }

  .vertical-line {
    width: 1px;
    height: 20px;
    margin: 3px auto;
    background: $theme-primary;
  }
  .bgcPurple {
    .el-card__header {
      background-color: rgb(194, 128, 255);
    }
  }
}
</style>
